package io.jee.medusa.servlet.resource;

import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.Charset;

import javax.servlet.http.HttpServletRequest;

import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.resource.ResourceTransformerChain;
import org.springframework.web.servlet.resource.ResourceTransformerSupport;
import org.springframework.web.servlet.resource.TransformedResource;

public class JsResourceTransformer extends ResourceTransformerSupport {
	
	private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

	@Override
	public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain)
			throws IOException {
		resource = transformerChain.transform(request, resource);

		String filename = resource.getFilename();
		if (!"js".equals(StringUtils.getFilenameExtension(filename))) {
			return resource;
		}
		
		byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
		String content = new String(bytes, DEFAULT_CHARSET);
		
		if(content.indexOf("${contextPath}")<0){
			return resource;
		}
		
		StringWriter writer = new StringWriter();
		
		writer.write(content.replaceAll("\\$\\{contextPath\\}", request.getContextPath()));
		
		return new TransformedResource(resource, writer.toString().getBytes(DEFAULT_CHARSET));
	}

}
